<script lang="ts" setup>
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';

import { Button, Popconfirm, Switch } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { UserApi } from '#/api/system/user';

import GroupTable from './group-table.vue';
import PasswordResult from './password-result.vue';
import UserForm from './user-form.vue';

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入查询关键字',
      },
      defaultValue: '',
      fieldName: 'query',
      label: '关键字',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
};
const gridOptions: VxeGridProps<UserApi.UserResult> = {
  columns: [
    { field: 'username', title: '用户名' },
    { field: 'nickname', title: '昵称' },
    { field: 'email', title: '邮箱' },
    { field: 'phone', title: '手机号' },
    { field: 'is_active', title: '激活状态', slots: { default: 'active' } },
    { field: 'is_superuser', title: '超级用户', slots: { default: 'superuser' } },
    {
      field: 'groups',
      title: '用户组',
      formatter: ({ cellValue }) => cellValue.map((item: { name: string }) => item.name).join(','),
    },
    { slots: { default: 'action' }, title: '操作', fixed: 'right' },
  ],
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) =>
        UserApi.listUser({
          page: page.currentPage,
          page_size: page.pageSize,
          ...formValues,
        }),
    },
  },
};

const [EditModal, editModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: UserForm,
});

const [ResetModal, resetModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: PasswordResult,
});
const [GroupModal, groupModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: GroupTable,
});

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  // gridEvents,
  gridOptions,
});

async function createUser(data: Partial<UserApi.UserResult>) {
  const row = await UserApi.createUser(data);
  gridApi.grid.insert(row);
  editModalApi.close();
}

async function updateUser({ id, data }: { data: Partial<UserApi.UserResult>; id: string }) {
  const record = await UserApi.updateUser(id, data);
  const row = gridApi.grid.getRowById(id);
  gridApi.grid.setRow(row, record);
  editModalApi.close();
}

async function updateUserGroups({ id, groups }: { groups: string[]; id: string }) {
  const record = await UserApi.updateUserGroups(id, { groups });
  const row = gridApi.grid.getRowById(id);
  gridApi.grid.setRow(row, record);
  groupModalApi.close();
}

async function resetPassword(row: UserApi.UserResult) {
  const password = await UserApi.resetPassword(row.id);
  resetModalApi.setData({ username: row.username, password }).open();
}

function openGroupTable(row: UserApi.UserResult) {
  groupModalApi.setData(row).open();
}

function openUserForm(row?: UserApi.UserResult) {
  editModalApi.setData(row ?? {}).open();
}
</script>

<template>
  <Page title="用户">
    <Grid>
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="() => gridApi.query()"> 刷新 </Button>
      </template>
      <template #toolbar-actions>
        <Button type="primary" @click="openUserForm()" title="新增用户"> 新增 </Button>
      </template>
      <template #active="{ row }">
        <Switch :checked="row.is_active" />
      </template>
      <template #superuser="{ row }">
        <Switch :checked="row.is_superuser" />
      </template>
      <template #action="{ row }">
        <Button type="link" @click="openUserForm(row)" title="修改用户信息">
          <IconifyIcon icon="fa6-solid:pen-to-square" />
        </Button>
        <Popconfirm @confirm="resetPassword(row)" title="确认重置密码？">
          <Button type="link" title="重置密码">
            <IconifyIcon icon="fa6-solid:key" />
          </Button>
        </Popconfirm>
        <Button type="link" @click="openGroupTable(row)" title="配置用户组">
          <IconifyIcon icon="fa6-solid:users" />
        </Button>
      </template>
    </Grid>
    <EditModal @update="updateUser" @create="createUser" />
    <ResetModal />
    <GroupModal @select="updateUserGroups" />
  </Page>
</template>
